
#include "file_export.h"

#include <assert.h>
#include <stdlib.h>

#include <assert.h>

#include "common/alloc.h"

//
// deserialization
//


struct FileDb
{
    struct FileHeader file_header;

    char * lex_tree_buffer;
};



static void ens_fread(FILE * fsrc, void * buf, size_t size)
{
    size_t read = fread(buf, 1, size, fsrc);
    if (read != size)
    {
        fprintf(stderr, "I/O error: can't read more bytes from the source file\n");
        abort();
    }
}


struct FileDb * load_file_db(FILE * fsrc)
{
    struct FileDb * db = xmalloc(sizeof(struct FileDb));

    ens_fread(fsrc, &db->file_header, sizeof(struct FileHeader));

    // read tree info
    db->lex_tree_buffer = xmalloc(db->file_header.tree_block_size);
    ens_fread(fsrc, db->lex_tree_buffer, db->file_header.tree_block_size);

    return db;
}

void free_file_db(struct FileDb * db)
{
    xfree(db->lex_tree_buffer);
    xfree(db);
}


void file_db_print_all(struct FileDb * db)
{
    assert(db->file_header.root_node_offset < db->file_header.tree_block_size);

    char * file_node_ptr = db->lex_tree_buffer + db->file_header.root_node_offset;
    struct FileNode * node = (struct FileNode *)file_node_ptr;
    struct FileEntry * entry_arr = (struct FileEntry *)(file_node_ptr + sizeof(struct FileNode));

    int i;

    fprintf(stdout, "root node has %d entries:\n", node->entry_count);

    for (i = 0; i < node->entry_count; ++i)
    {
        struct FileEntry * entry = entry_arr + i;

        fprintf(stdout, "#%02d: '%c'\n", i, entry->character);
    }
}
